Page({
  /**
   * 页面的初始数据
   */
  data: {
    userId: "",
    feedbackId: "",
    replies: [],
    feedbackInfo: null,
    isLoading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.feedback_id && options.user_id) {
      this.setData({
        feedbackId: options.feedback_id,
        userId: options.user_id,
      });
      this.getFeedbackDetail();
    } else {
      wx.showToast({
        title: "参数错误",
        icon: "none",
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        },
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getFeedbackDetail().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 获取反馈详情
   */
  getFeedbackDetail: function () {
    if (this.data.isLoading) return Promise.resolve();

    this.setData({ isLoading: true });

    // 同时请求两个接口：一个获取详情和回复，一个获取完整的反馈信息
    return Promise.all([this.getDetailAndReplies(), this.getFeedbackInfo()])
      .then(() => {
        this.setData({ isLoading: false });
      })
      .catch(() => {
        this.setData({ isLoading: false });
      });
  },

  /**
   * 获取反馈详情和回复
   */
  getDetailAndReplies: function () {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: "加载中...",
      });

      wx.request({
        url: "https://smartsound.top/api/feedback/v1/detail",
        method: "GET",
        data: {
          user_id: this.data.userId,
          feedback_id: this.data.feedbackId,
        },
        success: (res) => {
          if (res.data && res.data.code === 0) {
            const replies = res.data.replies || [];

            // 格式化回复时间
            if (replies && replies.length > 0) {
              replies.forEach((reply) => {
                if (reply.reply_time) {
                  reply.reply_time = this.formatTime(reply.reply_time);
                }
              });
            }

            this.setData({
              replies: replies,
            });

            resolve();
          } else {
            wx.showToast({
              title: "获取回复失败",
              icon: "none",
            });
            reject();
          }
        },
        fail: (err) => {
          console.error("获取反馈回复失败", err);
          reject();
        },
        complete: () => {
          wx.hideLoading();
        },
      });
    });
  },

  /**
   * 获取完整的反馈信息
   */
  getFeedbackInfo: function () {
    return new Promise((resolve, reject) => {
      wx.request({
        url: "https://smartsound.top/api/feedback/v1/list",
        method: "GET",
        data: {
          user_id: this.data.userId,
        },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.feedback_list) {
            // 从返回的列表中查找对应ID的反馈，确保转换为字符串进行比较
            const feedbackInfo = res.data.feedback_list.find(
              (item) =>
                String(item.feedback_id) === String(this.data.feedbackId)
            );

            if (feedbackInfo) {
              // 格式化时间
              if (feedbackInfo.submit_time) {
                feedbackInfo.submit_time = this.formatTime(
                  feedbackInfo.submit_time
                );
              }

              this.setData({
                feedbackInfo: feedbackInfo,
              });

              resolve();
            } else {
              wx.showToast({
                title: "未找到该反馈",
                icon: "none",
              });
              reject();
            }
          } else {
            wx.showToast({
              title: "获取反馈信息失败",
              icon: "none",
            });
            reject();
          }
        },
        fail: (err) => {
          console.error("获取反馈信息失败", err);
          reject();
        },
      });
    });
  },

  /**
   * 格式化时间
   */
  formatTime: function (timeString) {
    if (!timeString) return "";

    // 替换T为空格
    return timeString.replace("T", " ");
  },

  /**
   * 预览图片
   */
  previewImage: function () {
    if (this.data.feedbackInfo && this.data.feedbackInfo.attachment_url) {
      wx.previewImage({
        urls: [this.data.feedbackInfo.attachment_url],
        current: this.data.feedbackInfo.attachment_url,
      });
    }
  },

  /**
   * 返回上一页
   */
  navigateBack: function () {
    wx.navigateBack();
  },

  /**
   * 获取状态标签样式
   */
  getStatusClass: function (status) {
    if (status === "未处理") {
      return "status-pending"; // 红色
    } else if (status === "处理中" || status === "已回复") {
      return "status-replied"; // 蓝色
    } else {
      return "status-pending"; // 默认红色
    }
  },
});
